package com.core.entity;

import java.util.Date;
import java.util.List;

import com.core.utils.SqlKit;
import com.google.common.base.Joiner;
import com.google.common.collect.Lists;
import com.jfinal.aop.Before;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Table;
import com.jfinal.plugin.activerecord.TableMapping;
import com.jfinal.plugin.activerecord.tx.Tx;

public class BaseModel<M extends com.jfinal.plugin.activerecord.Model<M>> extends com.jfinal.plugin.activerecord.Model<M>{
	
	private static final long serialVersionUID = 8924183967602127690L;
	
	public static final String selectAll = "select * " ;
	public static final String select = "select " ;
	
	/**
	 * 获取表映射对象
	 */
	protected Table getTable() {
		return TableMapping.me().getTable(getClass());
	}
	
	@Before(Tx.class)//事务处理
	public void deleteByIds(String ids){
		String[] idArr = ids.split(",");
		for (String id : idArr) {
			deleteById(id);
		}
	}

	/**
	 * 需要创建时间的实体 保存方法
	 */
	public boolean save(M model) {
		return model.set("createTime", new Date()).save();
	}
	
	/**
	 * 分页查询
	 */
	public Page<M> paginate(int pageNumber, int pageSize,List<Condition> conditions) {
		Query query = SqlKit.buildQuery(getTable().getName(),conditions);
		return paginate(pageNumber, pageSize,selectAll,query.getSql(), query.getParamList().toArray()) ;
	}
	
	public Page<M> paginate(int pageNumber, int pageSize,Condition condition) {
		List<Condition> conditions = Lists.newArrayList();
		conditions.add(condition);
		Query query = SqlKit.buildQuery(getTable().getName(),conditions);
		return paginate(pageNumber, pageSize,selectAll,query.getSql(), query.getParamList().toArray()) ;
	}
	
	/**
	 * 分页查询
	 */
	public Page<M> paginate(int pageNumber, int pageSize,List<Condition> conditions,String[] sqlSelect) {
		Query query = SqlKit.buildQuery(getTable().getName(),conditions);
		return paginate(pageNumber, pageSize,select+Joiner.on(",").join(sqlSelect),query.getSql(), query.getParamList().toArray()) ;
	}

	/**
	 * 查询 多个条件
	 */
	public List<M> find(List<Condition> conditions) {
		Query query = SqlKit.buildQuery(getTable().getName(),conditions);
		return find(selectAll+query.getSql(), query.getParamList().toArray()) ;
	}
	
	/**
	 * 查询 单个条件
	 */
	public List<M> find(Condition condition) {
		List<Condition> conditions = Lists.newArrayListWithExpectedSize(1);// new ArrayList<Condition>();
		conditions.add(condition);
		Query query = SqlKit.buildQuery(getTable().getName(),conditions);
		return find(selectAll+query.getSql(), query.getParamList().toArray()) ;
	}

}
